<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            border: solid;

        }

        #box1 {
            width: 400px;
            height: 400px;
            top: 100px;
            left: 100px;
            position: relative;
            overflow: hidden;
        }

        #box2 {
            width: 100px;
            height: 100px;
            position: absolute;
        }
    </style>
</head>

<body>
    <div id="box1">box1
        <div id="box2">box2</div>
    </div>

    <script>
        const box1 = document.getElementById('box1')
        const box2 = document.getElementById('box2')

        // 1. 获取 box1 坐标

        const box1Pos = box1.getBoundingClientRect();

        // 3.何时移动
        box2.onmousedown = function (e) {
            //  获取box2坐标
            const box2Pos = box2.getBoundingClientRect()
            // 计算鼠标和box2的差值
            const x = e.clientX - box2Pos.left;
            const y = e.clientY - box2Pos.top;

            box2.onmousemove = function (e) {
                // 2.设置box2相对box1的坐标
                box2.style.left = e.clientX - box1Pos.left - x + 'px';
                box2.style.top = e.clientY - box1Pos.top - y + 'px';
            }
        }

        // 4.何时停止移动
        box2.onmouseup = function () {
            box2.onmousemove = null
        }


    </script>

</body>

</html>